package sendGoodsRecord

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/shopspring/decimal"
	"insighttracking/common/utils"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetSendGoodsRecordDetailApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetSendGoodsRecordDetailApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetSendGoodsRecordDetailApiLogic {
	hostname, _ := os.Hostname()
	return &GetSendGoodsRecordDetailApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetSendGoodsRecordDetailApiLogic) GetSendGoodsRecordDetailApi(req *types.IdReq) (resp *types.GetSendGoodsRecordDetailResp, err error) {
	// 获取基本信息
	sendGoodsRecordBoResp, err := service.SendGoodsRecordService.GetSendGoodsRecordApi(l.ctx, req.Id)
	if err != nil {
		return nil, err
	}
	// 获取详情数据
	entities, err := service.SendGoodsRecordDetailService.GetSendGoodsRecordDetailApi(l.ctx, req.Id)
	if err != nil {
		return nil, err
	}
	spuIdList := k.Map(entities, func(item *model.SendGoodsRecordDetailEntity, index int) int64 {
		return item.SpuID
	})
	spuEntities, err := service.SpuService.GetSpuByIdListApi(l.ctx, k.Distinct(spuIdList))
	var spuPriceMap = make(map[int64]decimal.Decimal)
	if err == nil && len(spuEntities) > 0 {
		spuPriceMap = k.ToMap(spuEntities, func(item *model.SpuEntity) (int64, decimal.Decimal) {
			return item.ID, item.PurchasePrice
		})
	}
	// 查询商品库存
	spuInventoryMap := service.SpuInventoryService.SpuInventoryBySpuIdListAPi(l.ctx, spuIdList, 0)
	var dataList = make([]types.SendGoodsRecordDetailModel, 0)
	for _, item := range entities {
		purchasePrice := spuPriceMap[item.SpuID]
		dataList = append(dataList, types.SendGoodsRecordDetailModel{
			ID:                      item.ID,                                                 // 主键id
			SendGoodsRecordID:       item.SendGoodsRecordID,                                  // 分拣单store_sorting主键id
			SpuID:                   item.SpuID,                                              // 商品,关联到spu表主键id
			SnapshotSpuName:         item.SnapshotSpuName,                                    // 快照商品名称
			SnapshotProductImageURL: item.SnapshotProductImageURL,                            // 快照产品图片
			SnapshotSpuType:         item.SnapshotSpuType,                                    // 快照商品类型,0表示基础商品,1表示加工商品
			SnapshotUnit:            item.SnapshotUnit,                                       // 快照单位
			SnapshotCategoryID:      item.SnapshotCategoryID,                                 // 快照分类id
			SnapshotCategory:        item.SnapshotCategory,                                   // 快照分类
			LossRate:                item.LossRate.StringFixed(2),                            // 快照损耗率
			OrdersCount:             item.OrdersCount.StringFixed(2),                         // 下单数量
			OutboundCount:           item.OutboundCount.StringFixed(2),                       // 出库数量
			OperateName:             item.OperateName,                                        // 出库员
			OperateID:               item.OperateID,                                          // 出库员id,关联到员工表
			Remark:                  item.Remark,                                             // 备注
			CreatedAt:               utils.TimestampToString(item.CreatedAt),                 // 创建时间
			UpdatedAt:               utils.TimestampToString(item.UpdatedAt),                 // 更新时间
			SnapshotPrice:           item.SnapshotPrice.StringFixed(2),                       // 商品单价
			OrdersAmount:            item.SnapshotPrice.Mul(item.OrdersCount).StringFixed(2), // 订单金额
			PurchasePrice:           purchasePrice.StringFixed(2),                            // 采购价格
			PurchaseAmount:          purchasePrice.Mul(item.OutboundCount).StringFixed(2),    // 采购金额
			SpuInventory:            spuInventoryMap[item.SpuID].StringFixed(2),              // 商品库存
		})
	}
	return &types.GetSendGoodsRecordDetailResp{
		BaseInfo: types.SendGoodsRecordModel{
			ID:            sendGoodsRecordBoResp.ID,                                 // 主键id
			OrderNo:       sendGoodsRecordBoResp.OrderNo,                            // 订单流水号
			CustomerID:    sendGoodsRecordBoResp.CustomerID,                         // 客户id,关联到enterprise_customer表主键id
			CustomerName:  sendGoodsRecordBoResp.CustomerName,                       // 客户id,关联到enterprise_customer表主键id
			TotalAmount:   sendGoodsRecordBoResp.TotalAmount.StringFixed(2),         // 订单金额
			TotalCount:    sendGoodsRecordBoResp.TotalCount.StringFixed(2),          // 订单商品数量
			WarehouseID:   sendGoodsRecordBoResp.WarehouseID,                        // 出库仓库,关联到warehouse表主键id
			WarehouseName: sendGoodsRecordBoResp.WarehouseName,                      // 出库仓库,关联到warehouse表主键id
			OrdersID:      sendGoodsRecordBoResp.OrdersID,                           // 关联到订单表id,orders表主键id
			OrdersOrderNo: sendGoodsRecordBoResp.OrdersOrderNo,                      // 关联到订单表id,orders表主键id
			OperateName:   sendGoodsRecordBoResp.OperateName,                        // 制单员
			OperateID:     sendGoodsRecordBoResp.OperateID,                          // 制单员id,关联到员工表
			Remark:        sendGoodsRecordBoResp.Remark,                             // 备注
			CreatedAt:     utils.TimestampToString(sendGoodsRecordBoResp.CreatedAt), // 创建时间
			UpdatedAt:     utils.TimestampToString(sendGoodsRecordBoResp.UpdatedAt), // 更新时间
		},
		DataList: dataList,
	}, nil
}
